package com.youku.mson.serializer;

public class JsonWriter {

	private StringBuilder builder = new StringBuilder();

	public void beginObject() {
		builder.append('{');
	}

	public void endObject() {
		builder.append('}');
	}

	public void beginArray() {
		builder.append('[');
	}

	public void endArray() {
		builder.append(']');
	}

	public void setBuffer(String s) {
		builder = new StringBuilder(s);
	}

	public StringBuilder getBuffer() {
		return builder;
	}

	public char charAt(int i) {
		if (i >= builder.length()) {
			throw new RuntimeException("索引越界，buffer长度为" + builder.length() + "，获取" + i + "索引字符");
		} else {
			return builder.charAt(i);
		}
	}

	public boolean endWith(String s) {
		return builder.toString().endsWith(s);
	}

	public void deleteCharAt(int i) {
		builder.deleteCharAt(i);
	}

	public void deleteEnd() {
		if (builder.length() == 0) {
			throw new RuntimeException("buffer没有任何元素，无法删除末尾字符");
		} else {
			builder.deleteCharAt(builder.length() - 1);
		}
	}

	@Override
	public String toString() {
		return builder.toString();
	}

	public void writeNull() {
		write(null);
	}

	public void write(Object obj) {
		builder.append(String.valueOf(obj));
	}

	public void writeString(Object obj) {
		builder.append('"').append(obj).append('"');
	}

	public void writeNumber(Object obj) {
		builder.append(obj);
	}

	public void writeComma() {
		builder.append(',');
	}

	public void writeColon() {
		builder.append(':');
	}

}
